package com.ruoyi.tb.lmt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.tb.lmt.domain.bo.TbWorkcategoryBo;
import com.ruoyi.tb.lmt.domain.vo.TbWorkcategoryVo;
import com.ruoyi.tb.lmt.domain.TbWorkcategory;
import com.ruoyi.tb.lmt.mapper.TbWorkcategoryMapper;
import com.ruoyi.tb.lmt.service.ITbWorkcategoryService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 检修类别Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-30
 */
@RequiredArgsConstructor
@Service
public class TbWorkcategoryServiceImpl implements ITbWorkcategoryService {

    private final TbWorkcategoryMapper baseMapper;

    /**
     * 查询检修类别
     */
    @Override
    public TbWorkcategoryVo queryById(Long ID) {
        return baseMapper.selectVoById(ID);
    }

    /**
     * 查询检修类别列表
     */
    @Override
    public TableDataInfo<TbWorkcategoryVo> queryPageList(TbWorkcategoryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TbWorkcategory> lqw = buildQueryWrapper(bo);
        Page<TbWorkcategoryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询检修类别列表
     */
    @Override
    public List<TbWorkcategoryVo> queryList(TbWorkcategoryBo bo) {
        LambdaQueryWrapper<TbWorkcategory> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TbWorkcategory> buildQueryWrapper(TbWorkcategoryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TbWorkcategory> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getLmtType()), TbWorkcategory::getLmtType, bo.getLmtType());
        lqw.like(StringUtils.isNotBlank(bo.getCategoryCode()), TbWorkcategory::getCategoryCode, bo.getCategoryCode());
        lqw.like(StringUtils.isNotBlank(bo.getWorkCategory()), TbWorkcategory::getWorkCategory, bo.getWorkCategory());
        return lqw;
    }

    /**
     * 新增检修类别
     */
    @Override
    public Boolean insertByBo(TbWorkcategoryBo bo) {
        TbWorkcategory add = BeanUtil.toBean(bo, TbWorkcategory.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public TbWorkcategory insertByBoRVo(TbWorkcategoryBo bo) {
        TbWorkcategory add = BeanUtil.toBean(bo, TbWorkcategory.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            return add;
        } else {
            throw new RuntimeException("添加失败");
        }
    }

    @Override
    public String selectIdByPidAndName(String id, String workKind, String lmtType) {
        return baseMapper.selectIdByPidAndName( id,  workKind,lmtType);

    }
    /**
     * 修改检修类别
     */
    @Override
    public Boolean updateByBo(TbWorkcategoryBo bo) {
        TbWorkcategory update = BeanUtil.toBean(bo, TbWorkcategory.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TbWorkcategory entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除检修类别
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<TbWorkcategory> treeBylmtType(String lmtType) {
        // 1.查询大机类型下的所有检修类别
        List<TbWorkcategory> list = baseMapper.selectList(Wrappers.<TbWorkcategory>lambdaQuery().eq(TbWorkcategory::getLmtType, lmtType));
        // 2.拼接为树形结构
        //获取父节点
        List<TbWorkcategory> collect = list.stream().filter(m -> m.getPid() == 0).map(
            (m) -> {
                m.setChildren(getChildrens(m, list));
                return m;
            }
        ).collect(Collectors.toList());
        return collect;
    }

    @Override
    public int copyBylmtType(Map<String, String> lmtTypeMap) {
        //从lmtTypeMap获取源大机类型
        if (StrUtil.isNotBlank(lmtTypeMap.get("source")) && ObjectUtil.isNotNull(lmtTypeMap.get("source"))) {
            List<TbWorkcategory> treeList = treeBylmtType(lmtTypeMap.get("source"));
            String[] targetLmtTypes = lmtTypeMap.get("target").split(",");
            for (int j = 0; j < targetLmtTypes.length; j++) {
                String target = targetLmtTypes[j];
                //获取treeList中节点为0的数组
                for (int i = 0; i < treeList.size(); i++) {
                    TbWorkcategory tbWorkcategory = treeList.get(i);
                    copyHandler(tbWorkcategory,target, 0L);
                }
            }
            return 1;
        } else {
            throw new RuntimeException("复制源目标不能为空");
        }
    }

    @Override
    public int removeByTree(String id) {
        //查询当前节点
        TbWorkcategory tbWorkcategory = baseMapper.selectById(id);
        deleteHandler(tbWorkcategory);
        return 1;
    }

    private void deleteHandler(TbWorkcategory tbWorkcategory) {
      //查询pid为tbWorkcategory ID 的节点
        List<TbWorkcategory> tbWorkcategoryList = baseMapper.selectList(Wrappers.<TbWorkcategory>lambdaQuery().eq(TbWorkcategory::getPid, tbWorkcategory.getId()));
        for (int i = 0; i < tbWorkcategoryList.size(); i++) {
            TbWorkcategory tbWorkcategory1 = tbWorkcategoryList.get(i);
            deleteHandler(tbWorkcategory1);
        }
        baseMapper.deleteById(tbWorkcategory);
    }


    private List<TbWorkcategory> getChildrens(TbWorkcategory root, List<TbWorkcategory> all) {
        List<TbWorkcategory> children = all.stream().filter(m -> {
            return Objects.equals(m.getPid(), root.getId());
        }).map(
            (m) -> {
                m.setChildren(getChildrens(m, all));
                return m;
            }
        ).collect(Collectors.toList());
        return children;
    }
    private TbWorkcategory copyHandler(TbWorkcategory tbWorkcategory,String target,Long pid) {
        //处理逗号分割的targetLmtType
        LoginUser loginUser = LoginHelper.getLoginUser();
        Long id = IdUtil.getSnowflakeNextId();
        tbWorkcategory.setLmtType(target);
        tbWorkcategory.setId(id);
        tbWorkcategory.setPid(pid);
        tbWorkcategory.setCreateTime(new Date());
        tbWorkcategory.setCreateBy(loginUser.getUsername());
        for (int i = 0; i < tbWorkcategory.getChildren().size(); i++) {
            TbWorkcategory tbWorkcategoryChild = tbWorkcategory.getChildren().get(i);
            copyHandler(tbWorkcategoryChild,target,id);
        }
        baseMapper.insert(tbWorkcategory);
        return tbWorkcategory;
    }
}
